// Created by Roman Novitsky on 24.04.2009


#region Imported Namespaces


using System.Diagnostics;
using System.Windows;
using System.Windows.Input;

using WtfManager.Framework;


#endregion


namespace WtfManager.UIManager.Commands
{
  public class SaveStateCommandHandler: Service, ICommandHandler
  {
    #region Properties/Indexers


    public ICommand Command
    {
      get
      {
        return StateManager.SaveStateCommand;
      }
    }


    public override string Description
    {
      get
      {
        return "Handles Save State Command";
      }
    }


    public override string Name
    {
      get
      {
        return "Save State Command Handler";
      }
    }

    private static StateManager StateManager
    {
      get
      {
        return (StateManager)WtfFramework.Instance.Services[typeof(StateManager)];
      }
    }


    #endregion


    #region Methods


    protected override void OnStateChnaged()
    {
    }


    protected override FrameworkComponentState OnLoad()
    {
      AddDependency(typeof(StateManager));

      return FrameworkComponentState.Loaded;
    }


    protected override void OnUnload()
    {
    }


    public bool CanExecuteCommand(object sender, object parameter)
    {
      Debug.Assert(IsInitialized, "SaveStateCommandHandler is not yet initialized.");

      if (StateManager == null)
      {
        return false;
      }

      var frameworkElement = sender as FrameworkElement;

      if(frameworkElement == null)
      {
        return false;
      }

      var fileName = parameter as string;

      if(string.IsNullOrEmpty(fileName))
      {
        fileName = StateManager.GetDefaultStateFileName(frameworkElement);
      }

      return !string.IsNullOrEmpty(fileName);
    }


    public void ExecuteCommand(object sender, object parameter)
    {
      Debug.Assert(IsInitialized, "SaveStateCommandHandler is not yet initialized.");

      var fileName = (string)parameter;
      var frameworkElement = sender as FrameworkElement;

      if (string.IsNullOrEmpty(fileName))
      {
        fileName = StateManager.GetDefaultStateFileName(frameworkElement);
      }

      StateManager.SaveState(fileName, frameworkElement);
    }


    protected override FrameworkComponentState OnInitialize()
    {
      return FrameworkComponentState.Initialized;
    }


    #endregion
  }
}